var config=require('../../config.js');
function load_userInfo(username,page){
  var that = this;
  findByUsername(username,page,function(){//表示根据username获取到的用户信息，存在则直接返回，否则就处理
    //当前处理表示从数据库中未查询到数据
    wx.getSetting({
      success: res => {
        ///if (res.authSetting['scope.userInfo']) {//表示已经授权过，说明以前存在过，直接查询数据库
        // console.log('我授权了');
       // }else{
          getUserInfo(page, function (userInfo, rawData, signature){
            wx.checkSession({
              success: function () {
                var SESSION_ID = wx.getStorageSync(config.SESSION_ID);
                if (SESSION_ID == null || undefined == SESSION_ID || SESSION_ID == "") {
                  wx.login({
                    success: function (data) {
                      getSesssion(username, data.code, userInfo, rawData, signature, page);
                    }
                  });
                } else {
                  signatureFunc(username, SESSION_ID, userInfo, rawData, signature, page)
                }
              }, fail: function () {
                 wx.login({
                   success: function (data) {
                     getSesssion(username, data.code, userInfo, rawData, signature, page);
                   }
                 });
              } 
            });
          });
        //}
      },
      fail: function () {//表示授权出现异常
        page.setData({
          url: '../images/tx.jpg'
        });
      }
    });  
  });
}  
  //获取微信信息
function getUserInfo(page,func){
  wx.getUserInfo({
    success(res) {
      var userInfo = res.userInfo;
      var rawData = res.rawData;
      var signature = res.signature;
      typeof func == 'function' && func(userInfo, rawData, signature);
    }, fail: function () {
      page.setData({
        url: '../images/tx.jpg'
      });
      wx.showModal({
        title: '警告',
        content: '您点击了拒绝授权，将获取到头像和昵称信息。请10分钟后再次点击授权，或者删除小程序重新进入。',
        success: function (res) {
          if (res.confirm) {
          }
        }
      });
    }
  });   
}
  
//根据username获取用户信息，若是存在，则设置数据，否则执行func函数
function findByUsername(username,page,func){
  wx.request({
    url: config.userDocuments + '/search/findByUsername',
    data: { username: username },
    header: { 'content-type': 'application/json' },
    success: function (res) {
      var data = res.data;
      var nickName = data.nickName;
      if (nickName) {//表示存在，直接获取，否则不获取 
        page.setData({
          nickName: data.nickName,
          url: data.avatar
        });
        var INFOS = {
          nickName: data.nickName,
          url: data.avatar
        }
        wx.setStorageSync("INFO", INFOS);
      }else{
        typeof func=='function'&&func();
      }
    }
  });  

}

//获取session
function getSesssion(username,code, userInfo, rawData, signature, page){
  wx.request({
    url: config.host_root_https + '/login/mini-program/' + config.tagName,
    data: {
      code: code
    },
    success(res) {
      //将获取到的SESSION_ID存放到域中
      var regex = /^[0-9a-z]{8}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{12}$/;
      var reg = new RegExp(regex);
      if (reg.test(res.data)) {//使用正则表达式验证，若是通过则继续获取数据
        wx.setStorageSync(config.SESSION_ID, res.data);
        signatureFunc(username, res.data, userInfo, rawData, signature, page)
      }
    }
  });
}
//验证用户和保存用户信息
function signatureFunc(username,sessionId, userInfo, rawData, signature, page){
  wx.request({
    url: config.mini_program +'/signature',
    data: {
      sessionId: sessionId, 
      rawData: rawData, 
      signature: signature
    },
    header: {
      'content-type': 'application/json'
    },
    success:function(res){
        if("Success"==res.data){ //表示验证成功后，存储用户信息
            wx.request({
              url: config.mini_program + '/user-info',
              method: 'get',
              data: {
                sessionId: sessionId,
                userInfo: userInfo
              }, header: {
                'content-type': 'application/json'
              },
              success: function (res) {
                if ('success'==res.data){
                  page.setData({
                    nickName: userInfo.nickName,
                    url: userInfo.avatarUrl
                  });
                  var INFOS = {
                    nickName: userInfo.nickName,
                    url: userInfo.avatarUrl
                  }
                  wx.setStorageSync("INFO", INFOS);
                }else{
                  page.setData({
                    url: '../images/tx.jpg'
                  });
                }
               // 
              }
            });
        }else{//验证失败
          page.setData({
            url: '../images/tx.jpg'
          });
        }
    }
  })
}

module.exports = {
  load_userInfo: load_userInfo
}
